package com.qianchang.microfinance.view.credit.data;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.register.RegisterActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;

public class EmailAuthenticationActivity extends BaseActivity  implements View.OnClickListener{
@BindView(R.id.det_Email)
ClearEditText det_Email;
@BindView(R.id.btn_email)
    Button btn_email;
@BindView(R.id.email_data)
ClearEditText email_data;
    @BindView(R.id.tv_get_phone_code)
    DTextView tv_get_phone_code;
    private CountDownTimer phoneDownTimer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_email_authentication);
        ButterKnife.bind(this);
        setTitleName("邮箱认证");
           btn_email.setOnClickListener(this);
        tv_get_phone_code.setOnClickListener(this);
    }

    private static boolean isEmail(String string) {
        if (string == null)
            return false;
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        if (m.matches())
            return true;
        else
            return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case  R.id.btn_email:
//
                if("".equals(det_Email.getText().toString().trim())){
                    Toast.makeText(this,"请输入邮箱",Toast.LENGTH_LONG).show();
                    return;
                }
                if(isEmail(det_Email.getText().toString()) == false){
                    Toast.makeText(this,"邮箱格式不正确",Toast.LENGTH_LONG).show();
                    return;
                }
                if("".equals(email_data.getText().toString().trim())){
                    Toast.makeText(this,"请输入验证信息",Toast.LENGTH_LONG).show();
                    return;
                }
                goEmail();

                break;
            case  R.id.tv_get_phone_code:
                if("".equals(det_Email.getText().toString().trim())){
                    Toast.makeText(this,"请输入邮箱",Toast.LENGTH_LONG).show();
                    return;
                }
                if(isEmail(det_Email.getText().toString()) == false){
                    Toast.makeText(this,"邮箱格式不正确",Toast.LENGTH_LONG).show();
                    return;
                }
                sendCaptcha();
                break;
        }
    }
    /**
     * 发送验证码
     */
    private void sendCaptcha() {
        show();
        HttpParams params = new HttpParams();
        params.put("email", det_Email.getText().toString().trim());
//email_data.getText().toString().trim()
        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.SEND_EMAIL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ToastUtil.getInstant().show(EmailAuthenticationActivity.this, getString(R.string.msg_indentity_code_send_success));
                    showRemainTime();
                } else {
                    ToastUtil.getInstant().show(EmailAuthenticationActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(EmailAuthenticationActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(EmailAuthenticationActivity.this, msg);
            }

        });
    }
    /**
     *
     */
    private void goEmail() {
        show();
        HttpParams params = new HttpParams();
        params.put("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        params.put("email", det_Email.getText().toString().trim());
        params.put("verifyCode", email_data.getText().toString().trim());
        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.COMFIR_EMAIL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ToastUtil.getInstant().show(EmailAuthenticationActivity.this, getString(R.string.msg_indentity_code_send_success));
                    finish();
                } else {
                    ToastUtil.getInstant().show(EmailAuthenticationActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(EmailAuthenticationActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(EmailAuthenticationActivity.this, msg);
            }

        });
    }
    //显示获取手机验证码倒计时
    private void showRemainTime() {
        tv_get_phone_code.setEnabled(false);
        phoneDownTimer = new CountDownTimer(DEFAULT_TIME, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                tv_get_phone_code.setText(temp + "S");//getString(R.string.remain_time) +
                tv_get_phone_code.setEnabled(false);
            }

            @Override
            public void onFinish() {
                tv_get_phone_code.setText(getString(R.string.btn_get_verify_code));
                tv_get_phone_code.setEnabled(true);
            }
        }.start();
    }
}
